<template>
    <!-- 对话框表单 -->
    <el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :destroy-on-close="true" v-model="dialogVisible"
        @close="handleClose">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="['.ba-operate-dialog']">
                {{ dialogTitle }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div class="ba-operate-form" :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'">
                <el-form ref="formRef" @keyup.enter="baTable.onSubmit(formRef)" :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'" :rules="rules" v-if="!baTable.form.loading">
                    <el-form-item label="上级id(不填为顶级)" prop="pid">
                        <el-select v-model="baTable.form.items!.pid" placeholder="请选择上级分类" clearable>
                            <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label"
                                :value="option.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="name" label="分类名称">
                        <el-input v-model="baTable.form.items!.name" type="string" placeholder="请输入分类名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="intro" label="简介">
                        <el-input v-model="baTable.form.items!.intro" type="textarea"
                            placeholder="请输入简介"></el-input>
                    </el-form-item>
                    <FormItem label="图标" type="image" v-model="baTable.form.items!.image" />
                    <FormItem label="图片" type="image" v-model="baTable.form.items!.big_image" />
                    <el-form-item prop="weight" label="权重">
                        <el-input-number v-model="baTable.form.items!.weight" :min="0" :step="1"
                            placeholder="0"></el-input-number>
                    </el-form-item>
                    <FormItem label="状态" v-model="baTable.form.items!.status" type="radio" :input-attr="{
                        border: true,
                        content: { 0: '禁用', 1: '启用' },
                    }" />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">取消</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)"
                    type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? '保存并编辑下一项' : '保存' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, inject, useTemplateRef, computed } from 'vue'
import type baTableClass from '/@/utils/baTable'
import type { FormItemRule } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import { buildValidatorData } from '/@/utils/validate'
import { useConfig } from '/@/stores/config'

const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass
const allCategories = inject('allCategories') as { value: any[] }

// 处理后的分类选项数据
const categoryOptions = computed(() => {
    if (!allCategories?.value || allCategories.value.length === 0) {
        return []
    }

    // 构建选项数据，保留层级结构
    const options = []

    // 创建ID到项目的映射
    const itemMap: Record<number, any> = {}
    allCategories.value.forEach(item => {
        itemMap[item.id] = item
    })

    // 递归构建树状结构并添加层级标识
    const buildTree = (parentId: number, level = 0) => {
        const children = allCategories.value
            .filter(item => item.pid === parentId)
            .sort((a, b) => (a.weight || 0) - (b.weight || 0))
        children.forEach(child => {
            // 为选项添加缩进
            const indent = '　'.repeat(level)
            options.push({
                value: child.id,
                label: indent + '└─ ' + child.name
            })

            // 递归处理子分类
            buildTree(child.id, level + 1)
        })
    }

    // 直接遍历pid为0的顶级分类，不添加额外的顶级分类选项
    allCategories.value
        .filter(item => item.pid === 0)
        .sort((a, b) => (a.weight || 0) - (b.weight || 0))
        .forEach(topItem => {
            // 顶级分类不需要缩进
            options.push({
                value: topItem.id,
                label: topItem.name
            })

            // 递归处理子分类
            buildTree(topItem.id, 1)
        })

    // 最后添加一个空选项，用于选择顶级分类
    options.unshift({ value: 0, label: '顶级分类(无上级分类)' })
    return options
})

// 计算对话框标题
const dialogTitle = computed(() => {
    if (!baTable.form.operate) return ''
    const operationMap: Record<string, string> = {
        'Add': '添加',
        'Edit': '编辑'
    }
    return operationMap[baTable.form.operate] + '分类'
})

// 计算对话框显示状态
const dialogVisible = computed({
    get: () => ['Add', 'Edit'].includes(baTable.form.operate!),
    set: (value: boolean) => {
        if (!value) {
            handleClose()
        }
    }
})

// 处理对话框关闭
const handleClose = () => {
    // 重置表单验证
    if (formRef.value) {
        formRef.value.resetFields()
    }
    // 调用baTable的toggleForm方法关闭表单
    baTable.toggleForm('')
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    name: [buildValidatorData({ name: 'required', title: '分类名称' })],
    intro: [buildValidatorData({ name: 'required', title: '简介' })],
    weight: [buildValidatorData({ name: 'number', title: '权重' })],
})
</script>

<style scoped lang="scss">
.image-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: var(--el-border-radius-small);
    box-shadow: var(--el-box-shadow-light);
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    overflow: hidden;
    width: 110px;
    height: 110px;
}

.image-uploader:hover {
    border-color: var(--el-color-primary);
}

.image {
    width: 110px;
    height: 110px;
    display: block;
}

.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
</style>
